//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.quickserver.net.qsadmin.gui;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.logging.Logger;
import org.quickserver.util.MyString;

public class QSAdminMain {
    private static Logger logger = Logger.getLogger(QSAdminMain.class.getName());
    private static final String NEW_LINE;
    private Socket socket;
    private InputStream in;
    private OutputStream out;
    private BufferedReader br;
    private BufferedWriter bw;
    private boolean connected = false;
    private boolean loggedIn = false;
    private boolean appendToConsole = true;
    private QSAdminGUI gui;
    private LinkedList receivedMsg;
    public static String VERSION_OF_SERVER;

    static {
        if (System.getProperty("org.quickserver.useOSLineSeparator") != null && System.getProperty("org.quickserver.useOSLineSeparator").equals("true")) {
            NEW_LINE = System.getProperty("line.separator");
        } else {
            NEW_LINE = "\r\n";
        }

        VERSION_OF_SERVER = "1.4.9";
    }

    public QSAdminMain() {
    }

    public boolean doLogin(String ipAddress, int port, String username, String password) throws IOException {
        this.connected = false;
        this.loggedIn = false;
        String backupVersionOfServer = VERSION_OF_SERVER;
        VERSION_OF_SERVER = null;
        logger.fine("Logging in to " + ipAddress + ":" + port);

        try {
            this.socket = new Socket(ipAddress, port);
            this.connected = true;
            this.in = this.socket.getInputStream();
            this.out = this.socket.getOutputStream();
            this.br = new BufferedReader(new InputStreamReader(this.in, "UTF-8"));
            this.bw = new BufferedWriter(new OutputStreamWriter(this.out, "UTF-8"));
            this.getGUI().setStatus("Connected");
            this.startSocketListener();
            String res = null;
            res = this.sendCommunicationSilent((String)null, false, true);
            if (!res.startsWith("+OK")) {
                throw new IOException(res.substring(4));
            } else {
                res = this.sendCommunicationSilent((String)null, false, true);
                if (!res.startsWith("+OK")) {
                    throw new IOException(res.substring(4));
                } else {
                    res = this.sendCommunicationSilent((String)null, false, true);
                    if (!res.startsWith("+OK")) {
                        throw new IOException(res.substring(4));
                    } else {
                        res = this.sendCommunicationSilent((String)null, false, true);
                        res = this.sendCommunicationSilent(username, false, true);
                        if (!res.startsWith("+OK")) {
                            if (res.startsWith("-ERR")) {
                                this.getGUI().setStatus("Error: " + res.substring(4));
                                throw new IOException("Bad QSAdmin Username! Server reply: " + res);
                            } else {
                                this.getGUI().setStatus("Protocol Error: " + res);
                                throw new IOException("Bad QSAdmin Username! Server reply: " + res);
                            }
                        } else {
                            this.getGUI().setStatus("Authorising..");
                            StringBuilder buffer = new StringBuilder();

                            for(int i = 0; i < password.length(); ++i) {
                                buffer.append('*');
                            }

                            this.getGUI().appendToConsole(buffer.toString());
                            res = this.sendCommunicationSilent(password, false, false);
                            if (res.startsWith("+OK")) {
                                this.getGUI().setStatus("Authorised");
                                this.loggedIn = true;
                                this.getGUI().setConsoleSend(true);
                                this.getGUI().updateConnectionStatus(true);
                                this.getGUI().appendToConsole("Checking version at host..");
                                VERSION_OF_SERVER = this.sendCommunicationSilent("version", false, true);
                                if (VERSION_OF_SERVER != null && VERSION_OF_SERVER.startsWith("+OK ")) {
                                    VERSION_OF_SERVER = VERSION_OF_SERVER.substring(4);
                                }

                                return true;
                            } else {
                                this.getGUI().setStatus("Error : " + res.substring(4));
                                throw new IOException(res.substring(4));
                            }
                        }
                    }
                }
            }
        } catch (UnknownHostException var9) {
            if (this.socket != null) {
                this.socket.close();
            }

            logger.warning("Error " + var9);
            this.connected = false;
            this.loggedIn = false;
            this.socket = null;
            this.in = null;
            this.out = null;
            this.br = null;
            this.bw = null;
            this.gui.setResponse("-ERR Unknown Host : " + var9.getMessage());
            this.gui.setConsoleSend(false);
            VERSION_OF_SERVER = backupVersionOfServer;
            return false;
        } catch (IOException var10) {
            if (this.socket != null) {
                this.socket.close();
            }

            logger.warning("Error " + var10);
            this.connected = false;
            this.socket = null;
            this.in = null;
            this.out = null;
            this.br = null;
            this.bw = null;
            this.gui.setResponse("-ERR " + var10.getMessage());
            this.gui.setConsoleSend(false);
            VERSION_OF_SERVER = backupVersionOfServer;
            return false;
        }
    }

    public void doLogout() throws IOException {
        if (this.socket == null) {
            throw new IllegalStateException("Not connected");
        } else {
            String res = this.sendCommunicationSilent("quit", false, true);
            if (res.startsWith("+OK")) {
                this.gui.setStatus("Disconnecting");
            } else {
                this.gui.setStatus("Error : " + res.substring(4));
            }

            this.clean();
        }
    }

    private void clean() {
        if (this.socket != null) {
            try {
                this.socket.close();
            } catch (Exception var2) {
                logger.warning("Error : " + var2);
            }

            this.socket = null;
        }

        this.in = null;
        this.out = null;
        this.br = null;
        this.bw = null;
        this.connected = false;
        this.loggedIn = false;
        this.gui.setConsoleSend(false);
        this.gui.setStatus("Disconnected");
        this.gui.updateConnectionStatus(false);
        this.setAppendToConsole(true);
    }

    public void sendCommand(String command, boolean echo) {
        logger.fine("Got command : " + command);
        if (!this.isConnected()) {
            this.gui.setResponse("-ERR Not connected yet.");
        } else {
            if (command != null && !command.equals("")) {
                if (this.socket == null) {
                    throw new IllegalStateException("Not connected");
                }

                if (echo) {
                    this.gui.appendToConsole(command);
                }

                command = command + NEW_LINE;

                try {
                    this.bw.write(command, 0, command.length());
                    this.bw.flush();
                } catch (Exception var4) {
                    this.gui.setResponse("-ERR " + var4.getMessage());
                }
            }

        }
    }

    public String readResponse(boolean multiLineResponse) {
        StringBuilder command = new StringBuilder();

        try {
            if (multiLineResponse) {
                String res = this.getReceivedMsg();
                if (res != null && !res.equals("+OK info follows")) {
                    return res;
                }

                if (res != null && res.equals("+OK info follows")) {
                    command.append("+OK ");
                    res = this.getReceivedMsg();
                }

                while(res != null && !res.equals(".")) {
                    logger.fine(res);
                    command.append(res + NEW_LINE);
                    res = this.getReceivedMsg();
                }
            } else {
                command.append(this.getReceivedMsg());
            }
        } catch (Exception var4) {
            command.append("-ERR " + var4.getMessage());
        }

        return command.toString();
    }

    public synchronized String sendCommunication(String command, boolean multiLineResponse, boolean echo) {
        logger.fine("Got command : " + command);
        if (!this.isConnected()) {
            this.gui.setResponse("-ERR Not connected yet.");
            return "-ERR Not connected yet";
        } else {
            if (command != null && !command.equals("")) {
                if (this.socket == null) {
                    throw new IllegalStateException("Not connected");
                }

                if (echo) {
                    this.gui.appendToConsole(command);
                }

                command = command + NEW_LINE;
                this.emptyReceivedMsg();

                try {
                    this.bw.write(command, 0, command.length());
                    this.bw.flush();
                } catch (Exception var5) {
                    this.gui.setResponse("-ERR " + var5.getMessage());
                    return null;
                }
            }

            command = this.readResponse(multiLineResponse);
            this.gui.setResponse(command);
            return command;
        }
    }

    public synchronized String sendCommunicationSilent(String command, boolean multiLineResponse, boolean echo) throws IOException {
        logger.fine("Got command : " + command);
        if (!this.isConnected()) {
            return "-ERR Not connected yet";
        } else if (this.socket == null) {
            throw new IllegalStateException("Not connected");
        } else {
            if (command != null && !command.equals("")) {
                if (echo) {
                    this.gui.appendToConsole(command);
                }

                command = command + NEW_LINE;
                this.emptyReceivedMsg();
                this.bw.write(command, 0, command.length());
                this.bw.flush();
            }

            return this.readResponse(multiLineResponse);
        }
    }

    public synchronized String sendCommunicationNoEcho(String command, boolean multiLineResponse) throws IOException {
        try {
            this.setAppendToConsole(false);
            logger.fine("Got command : " + command);
            if (!this.isConnected()) {
                return "-ERR Not connected yet";
            }

            if (this.socket == null) {
                throw new IllegalStateException("Not connected");
            }

            if (command != null && !command.equals("")) {
                command = command + NEW_LINE;
                this.emptyReceivedMsg();
                this.bw.write(command, 0, command.length());
                this.bw.flush();
            }

            command = this.readResponse(multiLineResponse);
        } catch (IllegalStateException var8) {
            throw var8;
        } catch (Exception var9) {
            throw new IOException("Exception Got : " + var9);
        } finally {
            this.setAppendToConsole(true);
        }

        return command;
    }

    public String toString() {
        if (this.socket == null) {
            return "Not connected";
        } else {
            StringBuilder info = new StringBuilder("Connected to ");
            info.append(this.socket.getInetAddress().getHostName());
            return info.toString();
        }
    }

    public boolean isConnected() {
        return this.connected;
    }

    public boolean isLoggedIn() {
        return this.loggedIn;
    }

    public void setGUI(QSAdminGUI gui) {
        this.gui = gui;
    }

    public QSAdminGUI getGUI() {
        return this.gui;
    }

    public void startSocketListener() {
        this.receivedMsg = new LinkedList();
        Thread t = new Thread() {
            public void run() {
                String rec = null;
                QSAdminMain.logger.info("Started");

                while(true) {
                    try {
                        rec = QSAdminMain.this.br.readLine();
                    } catch (IOException var3) {
                        QSAdminMain.logger.warning("Error : " + var3);
                        if (QSAdminMain.this.isConnected()) {
                            QSAdminMain.this.clean();
                        }
                        break;
                    }

                    if (rec == null) {
                        if (QSAdminMain.this.isConnected()) {
                            QSAdminMain.this.clean();
                        }
                        break;
                    }

                    QSAdminMain.this.receivedMsg.add(rec);
                    if (QSAdminMain.this.getAppendToConsole()) {
                        QSAdminMain.this.gui.appendToConsole(rec);
                    }
                }

                QSAdminMain.logger.info("Finished");
            }
        };
        t.setPriority(5);
        t.start();
    }

    public String getReceivedMsg() {
        while(this.receivedMsg.size() == 0 && this.isConnected()) {
            try {
                Thread.currentThread();
                Thread.sleep(50L);
            } catch (InterruptedException var2) {
                logger.warning("Error : " + var2);
            }
        }

        if (this.receivedMsg.size() != 0) {
            return (String)this.receivedMsg.removeFirst();
        } else {
            return null;
        }
    }

    public void emptyReceivedMsg() {
        this.receivedMsg.clear();
    }

    public float getServerVersionNo() {
        String ver = VERSION_OF_SERVER;
        if (ver == null) {
            this.gui.setResponse("-ERR Not connected yet");
            return 0.0F;
        } else {
            float version = 0.0F;
            int i = ver.indexOf(" ");
            if (i == -1) {
                i = ver.length();
            }

            ver = ver.substring(0, i);
            i = ver.indexOf(".");
            if (i != -1) {
                int j = ver.indexOf(".", i);
                if (j != -1) {
                    ver = ver.substring(0, i) + "." + MyString.replaceAll(ver.substring(i + 1), ".", "");
                }
            }

            try {
                version = Float.parseFloat(ver);
            } catch (NumberFormatException var5) {
                logger.warning("Error : " + var5);
                this.gui.setResponse("-ERR Corrupt QuickServer running @ host :" + var5.getMessage());
            }

            return version;
        }
    }

    public String getIpAddress() {
        return this.socket == null ? null : this.socket.getInetAddress().getHostName();
    }

    public boolean getAppendToConsole() {
        return this.appendToConsole;
    }

    public void setAppendToConsole(boolean appendToConsole) {
        this.appendToConsole = appendToConsole;
    }
}
